package netty.bio;

import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author cyt
 * @create 2020-11-04 10:32
 */
public class BioServer {

    public static void main(String[] args) throws IOException {

        ExecutorService service = Executors.newCachedThreadPool();
        ServerSocket socket = new ServerSocket(9999);
        System.out.println("服务器启动了");

        while (true) {

            System.out.println("线程信息 id : - > " + Thread.currentThread().getId() + " 名字 - >" + Thread.currentThread().getName());

            System.out.println("等待客户端连接 - >>>> ");

            Socket accept = socket.accept();

            System.out.println("连接到一个客户端");

            service.execute(new Runnable() {
                @Override
                public void run() {
                    handler(accept);
                }
            });
        }
    }

    public static void handler(Socket socket) {
        try {
            System.out.println("线程信息 id : - > " + Thread.currentThread().getId() + " 名字 - >" + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];

            InputStream inputStream = socket.getInputStream();
            while (true) {
                System.out.println("线程信息 id : - > " + Thread.currentThread().getId() + " 名字 - >" + Thread.currentThread().getName());
                System.out.println("read  - >>> ");

                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
